

function shadedErrorBar2(x,y,er,clr,displayname)
% function draws shaded continuous errorbars
% er is the deviation from y (not the actual value); if you have
% asymmetrical errors, then the first column is the lower bound, second
% column is upper bound

if size(x,1) == 1
    x = x';
end
if size(y,1) ~=  size(x,1)
    y = y';
end
if size(er,1) ~= size(x,1)
    er = er';
end

if nargin < 4
    clr = [.5,.5,.5];
end

% plot piece-wise if there are gaps in the data:
ind = isnan(x) | isnan(y);
d = [-1;diff(ind)];
if ind(1)
    d(1) = 0;
end
if ~(ind(end))
    d(end) = 2;
end
starts = find(d == -1);
ends = find(d == 1)-1;
ends = [ends;find(d==2)];
if length(starts) < length(ends)
    starts = [starts,ends(end)];
end
for n = 1:length(starts)
    X = x(starts(n):ends(n));
    Y = y(starts(n):ends(n));
    
    ER = er(starts(n):ends(n),:);
    if length(Y) == 1
        if size(ER,2) == 1
            errorbar(X,Y,ER,'.','color',clr,'linewidth',2,'MarkerSize',15);
        elseif size(ER,2) == 2
            errorbar(X,Y,ER(1),ER(2),'.','color',clr,'linewidth',2,'MarkerSize',15);
        end
    else
        if size(ER,2) == 1
            h = fill([X;flipud(X)],[Y-ER;flipud(Y+ER)],clr,'linestyle','none','FaceAlpha',.3);
        elseif size(ER,2) == 2
            h = fill([X;flipud(X)],[Y-ER(:,1);flipud(Y+ER(:,2))],clr,'linestyle','none','FaceAlpha',.3);
        end
        h.FaceAlpha = .3;
    end
    hold on
end
if nargin < 5 || isempty(displayname)
    line(x,y,'color',clr,'linewidth',2)
else
    line(x,y,'color',clr,'linewidth',2,'displayname',displayname)
end
